package main

import (
	"bufio"
	"context"
	"fmt"
	"github.com/gorilla/websocket"
	"go.bug.st/serial/enumerator"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

var portName = "COM4"
var isTest = "N"

// 用于从串口读取数据的通道
var dataChannel = make(chan []byte)
var wsChannel = make(chan bool)

func main() {
	//获取串口列表
	ports, err := enumerator.GetDetailedPortsList()
	if err != nil {
		log.Fatal(err)
	}
	if len(ports) == 0 {
		log.Fatal("No serial ports found!")
	}
	for _, port := range ports {
		log.Printf("串口编号：%s，串口名称: %s\n", port.Product, port.Name)
		if strings.Contains(strings.ToLower(port.Product), "serial") {
			portName = port.Name
		}
	}

	// 创建一个标准输入的扫描器
	scanner := bufio.NewScanner(os.Stdin)

	log.Print("请输入是否仅模拟数据使用Y/N,默认N: ")
	scanner.Scan() // 读取一行输入
	scanIsTest := scanner.Text()
	if scanIsTest != "" {
		isTest = strings.ToUpper(scanIsTest)
	}

	if isTest == "Y" {
		go func() {
			defer func() { // 必须使用 defer
				if r := recover(); r != nil {
					fmt.Println("Recovered:", r)
				}
			}()
			getTestData()
		}()
	} else {
		log.Print("请选择串口名称，默认" + portName + ": ")
		scanner.Scan() // 读取一行输入
		scanPortName := scanner.Text()
		if scanPortName != "" {
			portName = strings.ToUpper(scanPortName)
		}

		go func() {
			defer func() { // 必须使用 defer
				if r := recover(); r != nil {
					fmt.Println("运行异常:", r)
				}
			}()
			getRs232Data()
		}()
	}

	http.HandleFunc("/ws", HandleWebSocket)
	log.Println("串口数据连接服务已启动：6161")
	if err := http.ListenAndServe(":6161", nil); err != nil {
		log.Fatal("串口数据连接服务启动失败: ", err)
	}

	// 监听中断信号
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	log.Println("Server is start.......")
	// 等待中断信号
	sig := <-signalChan
	log.Printf("Received signal: %s. Shutting down...\n", sig.String())

	// 创建上下文和超时时间
	_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

}
